Component({
  runTimerid: 0,
  properties: {
    percent: {
      type: Number,
      value: 0,
      observer: function (newVal, oldVal) {
        console.log(newVal);
        this.draw(newVal);
      },
    },
  },
  data: {
    percentage: 0,
    animTime: 0,
  },
  methods: {
    run(c, w, h) {
      var num = ((2 * Math.PI) / 100) * c - 0.5 * Math.PI;
      this.ctx2.arc(w, h, w - 8, -0.5 * Math.PI, num);
      this.ctx2.setStrokeStyle("#09bb07");
      this.ctx2.setLineWidth("16");
      this.ctx2.setLineCap("butt");
      this.ctx2.stroke();

      this.ctx2.beginPath();
      this.ctx2.setFontSize(40);
      this.ctx2.setFillStyle("#b2b2b2");
      this.ctx2.setTextAlign("center");
      this.ctx2.setTextBaseline("middle");
      this.ctx2.fillText(c + "%", w, h);

      this.ctx2.draw();
    },
    canvasTap(start, end, time, w, h) {
      start++;
      if (start > end) return false;
      this.run(start, w, h);
      this.runTimerid = setTimeout(() => {
        this.canvasTap(start, end, time, w, h);
      }, time);
    },
    draw(percent) {
      const id = "runCanvas";
      const animTime = 500;
      if (percent > 100) return;
      if (!this.ctx2) {
        const ctx2 = wx.createCanvasContext(id, this);
        this.ctx2 = ctx2;
      }

      let oldPercentValue = this.data.percentage;
      this.setData({
        percentage: percent,
        animTime: animTime,
      });
      var time = this.data.animTime / (this.data.percentage - oldPercentValue);

      const query = wx.createSelectorQuery().in(this);
      query
        .select("#" + id)
        .boundingClientRect((res) => {
          var w = parseInt(res.width / 2);
          var h = parseInt(res.height / 2);

          if (this.runTimerid) clearTimeout(this.runTimerid);

          this.canvasTap(oldPercentValue, percent, time, w, h);
        })
        .exec();
    },
  },
});
